﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace OCRTheNewHope
{
    public static class OldFileOperations
    {

        /// <summary>
        ///   Returns gray-scale digit images from a given MNIST data source.
        /// </summary>
        /// 
        /// <param name="path">Path of MNIST data source.</param>
        /// <returns>The grays-scale images in the given MNIST data source path.</returns>
        /// 
        public static byte[][,] ReadImages(string path, int skip = 0, int count = 0)
        {
            byte[][,] rVal;

            using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
            {
                int length = (int)b.BaseStream.Length;

                int magicNumber = IPAddress.NetworkToHostOrder(b.ReadInt32());
                int numItems = IPAddress.NetworkToHostOrder(b.ReadInt32());
                int numRows = IPAddress.NetworkToHostOrder(b.ReadInt32());
                int numCols = IPAddress.NetworkToHostOrder(b.ReadInt32());

                rVal = count < 1 ? new byte[numItems][,] : new byte[count][,];

                b.BaseStream.Seek(skip * numRows * numCols, SeekOrigin.Current);

                for (int k = 0; k < rVal.Length; k++)
                {
                    byte[,] tempArray = new byte[numRows, numCols];

                    for (int i = 0; i < numRows; i++)
                        for (int j = 0; j < numCols; j++)
                            tempArray[i, j] = b.ReadByte();

                    rVal[k] = tempArray;
                }
            }

            return rVal;
        }

        /// <summary>
        ///   Returns labels of gray-scale digit images from a given MNIST data source.
        /// </summary>
        /// 
        /// <param name="path">Path of MNIST data source.</param>
        /// <returns>The labels of images from the given MNIST data source path. .</returns>
        /// 
        public static int[] ReadLabels(string path, int skip = 0, int count = 0)
        {
            int[] rVal;

            using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
            {
                int magicNumber = IPAddress.NetworkToHostOrder(b.ReadInt32());
                int numItems = IPAddress.NetworkToHostOrder(b.ReadInt32());

                rVal = count < 1 ? new int[numItems] : new int[count];

                b.BaseStream.Seek(skip, SeekOrigin.Current);

                for (int i = 0; i < rVal.Length; i++)
                {
                    rVal[i] = b.ReadByte();
                }
            }

            return rVal;
        }
    }
}
